package com.speedfall;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.util.ArrayList;
import java.util.List;

public class PreMainAgent extends BaseCtl{
	final static String prefix = "com.sy.core";
	public static void premain(String string,Instrumentation inst) {
		 classNameList=readClass();
		 methodNameList=readMethod();
		 Iterable<String> iterable = classNameList;
		 AgentBuilder.Transformer transformer = new AgentBuilder.Transformer() {
	            public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
	                                                    TypeDescription typeDescription,
	                                                    ClassLoader classLoader) {
	                return builder
	                        .method(ElementMatchers.any()) // 拦截任意方法
	                        .intercept(MethodDelegation.to(MyInteceptor.class)); // 委托
	            }

	        };
		
	        new AgentBuilder
            .Default()
            .type(ElementMatchers.<TypeDescription>nameStartsWith(prefix)) // 指定需要拦截的类
            .transform(transformer)
            .installOn(inst);
	}

	/**
	 * 读入文件获取所有的方法名
	 */
	private static List<String> readMethod(){
		List<String> methodList = new ArrayList<String>();
		String filePath="F:/method.config";
		//String filePath="method.config";
		FileReader fileReader=null;
		BufferedReader bf = null;
		try {
			fileReader= new FileReader(filePath);
			bf = new BufferedReader(fileReader);
			String line = bf.readLine();
			while(line!=null){
				methodList.add(line);
				line = bf.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				bf.close();
				fileReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return methodList;
	}

	/**
	 * 读入文件获取所有的类名
	 */
	private static List<String> readClass(){
		List<String> methodList = new ArrayList<String>();
		String filePath="F:/class.config";
		//String filePath="class.config";
		FileReader fileReader=null;
		BufferedReader bf = null;
		try {
			fileReader= new FileReader(filePath);
			bf = new BufferedReader(fileReader);
			String line = bf.readLine();
			while(line!=null){
				methodList.add(line);
				line = bf.readLine();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				bf.close();
				fileReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return methodList;
	}
}
